/*
Realistic Unit Modification v4.0 Dialog 
v4.0.0.1 [ALPHA]
Concept & Development by Draper & Raps | [VRC]
*/

private ["_weaponclass","_helo","_helocallsign","_type","_class","_pilot","_gunner","_cMedium","_CanonMedium","_cLong","_mDefault","_mDeuces","_mQuads","_mSixShooter","_cFireRate","_mFireRate","_cRoF","_mRoF","_laser","_tar","_grp","_wpAH","_dir","_canFire","_heloAmmo","_imgHelo","_title","_tickerText","_text","_altAdj","_aimingQuality","_vehMagazine","_dir2","_dir","_helodir","_targetpos","_targetdistance","_varIntersect"];

/* define variables used */
_weaponclass = _this select 0;
_helo = _this select 1;
_helocallsign = _this select 2;
_type = _this select 3;
_class = typeof _helo;
_gunner = gunner _helo;
_pilot = driver _helo;
_grp = group _pilot;

_canFire = false;
varIntersect = nil;
varGunner = true; 
varFireCanon = nil;
dialogOver = nil;

/* forces the server side helo object to become client side. */
[_helo] joinSilent player;
[_helo] joinSilent grpNull;
[_helo] joinSilent _grp;
_helo setBehaviour "SAFE";
_helo setCombatMode "BLUE";

/* SFS fire duration */
_cShort = 25;
_cMedium = 35;
_cLong = 50;

/* ATGM fire duration */
_mDefault = 1;
_mDeuces = 2;
_mQuads = 4;
_mSixShooter = 6;

/* Default fire rate for SFS and ATGM */
_cFireRate = _cMedium;
_mFireRate = _mDeuces;

/* SFS fire rate delay */
_cRoF = 0.016; /* higher value = lower rate of fire; lower value = higher rate of fire. */

/* ATGM fire rate delay */
_mRoF = 4.5; /* higher value = slower rate of fire; lower value = higher rate of fire. */

RUM_AHelBobUpLocal = {
	/* this is for line of sight to the target so that the helo can be hidden to allow for bobbing up over just the top of the terrain to send the shot */
	_pilot sidechat format["%1 - unmasking from cover",_helocallsign];
	[_helo] spawn {
		_helo = _this select 0;
		_varIntersect = true;
		_varLoS = true;
		while {_varIntersect or _varLoS} do {
			_varIntersect = terrainIntersect [getPosASL _helo, getPosASL (laserTarget player)];
			_varLoS = lineIntersects [getPosASL _helo, getPosASL (laserTarget player), _helo];
			//_varLoSObj = lineIntersectsWith [getPosASL _helo, getPosASL (laserTarget player), _helo];
			//hintSilent format["Helo is masked?: %1\n%3s alititude is: %2\n%3s direction is: %4\nLasers direction is: %5\nSomething in the way: %6\n--- Objects in view ---\n%7",_varIntersect, round(getPosATL _helo select 2),_helo, getDir _helo, getDir (laserTarget player),_varLoS,_varLoSObj];
			hintSilent format["%1, %2, %3",_varIntersect,_varLoS,round(getPosATL _helo select 2)];
			sleep 0.5;
		};
		RUM_clearedtofire = true;
	};
	RUM_clearedtofire = false;
	
	/* make the helo bob up to fire on target, this is used with the LoS (line of sight) script above */
	_altAdj = 0;
	waitUntil{
		sleep 1.5;
		hint format["%1, %2, %3",_grp,_altAdj,0];
		_helo domove getpos _helo;
		_wpAH=_grp addWaypoint [_helo, 0];
		_wpAH setWaypointType "MOVE";
		_wpAH setWaypointCompletionRadius 0;
		_helo flyInheight RUM_AHEL_flyStationHeight + _altAdj;
		_altAdj = _altAdj + 5;
		RUM_clearedtofire or (getposATL _helo select 2 > 500);
	};

	/* final move to clear horizon */
	_altAdj = 10;
	_helo domove getpos _helo;
	_wpAH=_grp addWaypoint [_helo, 0];
	_wpAH setWaypointType "MOVE";
	_wpAH setWaypointCompletionRadius 0;
	_helo flyInheight (getPosATL _helo select 2) + _altAdj;
	
	/* waits till the bob-up movement is complete */
	waituntil{
		sleep 0.5;
		((getPosATL _helo select 2) >= ((RUM_AHEL_flyStationHeight + _altAdj) - 6.5));
	};
	
	/* sends the all clear to process fire orders */
	_canFire = true;
	varIntersect = nil;
};

RUM_AHelBobDwnLocal = {
	/* this will allow the helo to return to its stationed height */
	_pilot sidechat format["%1 - remasking behind cover",_helocallsign];
	_helo doMove [(getPos _helo select 0), (getPos _helo select 1), RUM_AHEL_flyStationHeight];
	_wpAH=_grp addWaypoint [_helo, 0];
	_wpAH setWaypointType "MOVE";
	_wpAH setWaypointCompletionRadius 0;
	_helo flyInHeight RUM_AHEL_flyStationHeight;

	waituntil{
		sleep 0.5;
		((getPosATL _helo select 2) >= (RUM_AHEL_flyStationHeight + 6.5));
	};
	_canFire = false;
};

RUM_fn_AHEL_FireCanon = {
	/* determine if the target is to far away for guns. TODO - maybe auto switch to missile instead... ???? */
	if ((_targetdistance > 1200) || (_targetdistance < 175)) then {
		_pilot sidechat format["Operation Cancelled. Target is either outside effective range or too close. Target distance: %1 meters",(round _targetdistance)];
		if (true) exitwith {};
	} else {
		/* this is for SFS (supporessive fire support) and with the gun tracking allows the laser target to be shot by canons */
		_aimingQuality = gunner _helo AimedAtTarget [laserTarget player,"gatling_20mm"];
		
		/* remove the missiles that can be fired at the laser target, thus leaving guns */
		_helo removemagazines "24Rnd_PG_missiles";
		
		/* set the behavios of the helo units to allow for firing - this is done now to allow time for the unit to track the laser designator */
		_helo setBehaviour "STEALTH"; 
		_helo setCombatMode "GREEN";
		_helo disableAI "MOVE";
		_helo disableAI "TARGET";
		
		/* if the unit is a pilot, then he will obviously have skillz, just seems right when you think about it... only the best become pilots (think hard... :P) */
		_helo setskill 1;
		
		sleep 2.5;

		/* sets up the loop for the canon fire, rate of fire, and fire rate... also checks for hit pobablility on laser target */
		_pilot sidechat "20mm Down Range!";
		waitUntil {
			sleep _cRoF;
			
			/* how clean is the shot - more work to be done here... TODO */
			_aimingQuality = gunner _helo AimedAtTarget [laserTarget player,_weaponclass];
			
			/* checks to make sure the player still has the laser pointed and turned on... */
			if (!isNull (laserTarget player)) then {
				/* verifies the hit chance */
				if (_aimingQuality > 0.5) then {
					_helo fireAtTarget [laserTarget player,_weaponclass];
				};
			} else {
				_pilot sideChat "Not able to Shoot, no angle on target";
			};
			_cFireRate = _cFireRate - 1;
			
			/* ends the waituntil loop when reached */
			_cFireRate <= 0;
		};
		/* resets the behavior to before the shot. */
		_helo setBehaviour "STEALTH"; 
		_helo setCombatMode "BLUE";
		_helo enableAI "MOVE";
		_helo enableAI "TARGET";
			
		sleep 3.5;
		/* adds back the missiles that were taken at the start of the canon fire - restores only what it had prior, not a full load. */
		_helo addMagazine (_heloAmmo select 2);
		
		/* variable set for other functions that are waiting. */
		varGunner = false;
		terminate _spawnGunTracker;
		// terminate _spawnLoS;
	};
};

RUM_AHelFireMissileFn = {
	/* checks for hit probablility */
	_aimingQuality = gunner _helo AimedAtTarget [laserTarget player,"missiles_DAGR"];
	
	/* checks for distance to target. TODO - verify missile range to target, hellfire missiles had approximately the same range */
	if (_helo distance laserTarget player < 8000) then {
		/* verifies the hit chance */
		// if (_aimingQuality > 0.3) then {
			/* loop for single to multi missile fire support */
			waitUntil{
				sleep _mRoF;
				_helo setVectorUp [.20,0,1];
				_helo fireAtTarget [laserTarget player,_weaponclass];
				_mFireRate = _mFireRate - 1;
				/* ends the wait loop when value reached */
				_pilot sidechat "Beam Rider!";
				_mFireRate <= 0;
			};
		// } else {
			// _pilot sidechat "Aborting ATGM Mission, poor firing solution";
		// };
	} else {
		_pilot sidechat "Aborting ATGM Mission, No Shot, distance is too far...";
	};
	
	/* variable set for other functions that are waiting. */
	// _helo setBehaviour "SAFE"; 
	// _helo setCombatMode "GREEN";
	// _helo enableAI "MOVE";
	varGunner = false;
	terminate _spawnGunTracker;
	// terminate _spawnLoS;
};
hint "5";
/* /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\  Start of Script  /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ */
/* runs RUM dialog */
["callfire",[player,driver _helo,_helocallsign,_type]] execVM (RUM_PATH + "AHel\radiodialogs.sqf");
sleep (1 + random 3);

waitUntil{sleep 0.5; !isNil "dialogOver"};

/* displays the current helo's ammo stores and brings it on screen; also stores it for later use when adding and removing missiles */
_heloAmmo = magazinesAmmo _helo;

/* generate text formatting */
_imgHelo = "<img color='#006CB9' size='1.6' shadowColor='#FFFFFF' image='\a3\ui_f\data\map\Markers\NATO\b_air.paa' align='left'/>"; //o_air.paa

_title = format["%1<t color='#006CB9' size='1.3' shadow='1' shadowColor='#000000' align='center'>%2 Ammo</t>",_imgHelo,_helocallsign];
_tickerText = format ["%1",_title];
hint parseText _tickerText;

_text = format["<t color='#006CB9' size='1.1' shadow='1' shadowColor='#000000' align='right'>%1 Gun Rounds</t>",(_heloAmmo select 0 select 1)];
_tickerText = format ["%1<br />%2",_tickerText,_text];
hint parseText _tickerText;

_text = format["<t color='#006CB9' size='1.1' shadow='1' shadowColor='#000000' align='right'>%1 AA Misiles</t>",(_heloAmmo select 1 select 1)];
_tickerText = format ["%1<br />%2",_tickerText,_text];
hint parseText _tickerText;

_text = format["<t color='#006CB9' size='1.1' shadow='1' shadowColor='#000000' align='right'>%1 AT Misiles</t>",(_heloAmmo select 2 select 1)];
_tickerText = format ["%1<br />%2",_tickerText,_text];
hint parseText _tickerText;
sleep 3.5;

/* exits script if ammo of th etype the mission calls for is out */
if (0 == _helo ammo _weaponclass) exitWith {_pilot sidechat "Winchester";};

/* start laser detection */
for [{_n = 0},{_n < 30},{_n=_n + 1}] do {
	if (!isNull (lasertarget player)) then {
		// laserTarget player = laserTarget player;
		_n = 30;
	};
};

/* check to see if the target it in the ROE Zone */
if !([position laserTarget player] call ROEzone) exitwith {_pilot sidechat "Target is in a restricted zone, check your ROE intel.";};

/* this is the gun tracking script... when running, the canon will follow the laser designators laser. */
_spawnGunTracker = [_helo] spawn {
	_helo = _this select 0;
	while{varGunner} do {
		if (!isNull (laserTarget player)) then {
			_helo lookAt (laserTarget player);
		};
		sleep 0.25;
	};
};

/* checks to make sure the laser is active before the helo is instructed, else exits */
if (isNull (laserTarget player)) then {
	if (true) exitWith {_pilot sidechat "No sparkle, ending mission";};
} else {
	_pilot sideChat "Receiving Target Handoff, standby...";
	sleep 0.5;
	/* positions the helo in the correct direction - TODO make adjustments to better the action. */
	_dir = ((getpos laserTarget player select 0)-(getpos _helo select 0)) atan2 ((getpos laserTarget player select 1)-(getpos _helo select 1));
	_dir = 10 * round (_dir/10);
	sleep 0.5;
	_pilot sidechat "Target located";
	_helodir = 10 * round ((getdir _helo)/10);
	
	/* turns the helo into the right direction before fire missions */
	while {!(_dir == _helodir)} do {
		if(_dir < _helodir) then {
			_dir2 = _helodir - 2.5;
		} else {
			_dir2 = _helodir + 2.5;
		};
		_helodir = _dir2;
		_helo setdir _dir2;
		sleep 0.02;	
	};
	
	_pilot sidechat "Target Handoff Received.";

	/* check distance from helo to target */
	_targetpos = [getPos laserTarget player select 0,getPos laserTarget player select 1,0];
	_targetdistance = _targetpos distance [getPos _helo select 0, getPos _helo select 1, 0];
	_pilot sidechat format ["%2 meters away",_dir, _targetdistance];

	switch (_type) do {
		/* create variable switched weapons for different firing types */
		/* =================================== SFS - Canon Fire ========================================== */
		case "SFS": { /* fires canon/machinegun at the the lased target */
			[] call RUM_AHelBobUpLocal;
			
			waituntil{
				sleep 0.5; 
				_canFire;
			};
			[] call RUM_fn_AHEL_FireCanon;
			
			_spawnGunTracker = [_helo] spawn {
				_helo = _this select 0;
				while{(!isNull (laserTarget player))} do {
					_helo lookAt (laserTarget player);
					sleep 0.025;
				};
			};

			_menuAction1 = player addAction ["Fire Canon",RUM_PATH + "AHel\fireCanon.sqf",[_helo,_cRoF,_cFireRate,_weaponclass]];
			
			waitUntil{
				sleep 0.15;
				(isNull (laserTarget player));
			};
			terminate _spawnGunTracker;

			player removeAction _menuAction1;
			// player removeAction _menuAction2;
		};

		/* =================================== ATGM - Laser Guided Missile =================================== */
		case "ATGM": { /* fires laser guided missile at the the lased target */
			[] call RUM_AHelBobUpLocal;

			waituntil{sleep 0.5; _canFire};

			if(RUM_clearedtofire) then {
				[] call RUM_AHelFireMissileFn;
				_menuAction2 = player addAction ["Fire ATGM",RUM_PATH + "AHel\fireMissile.sqf",[_helo,_weaponclass]];
			
				waitUntil{
					sleep 0.15;
					(isNull (laserTarget player));
				};
				player removeAction _menuAction2;
			}else{
				_pilot sidechat toUpper("Target Obscured");
			};			
		};	

		/* =================================== FFAR - Rocket Barrage ================================ */
		case "FFAR": { /* if equipped, will fire folding fin arial rockets at the lased target */
		
		};	
	};
	waitUntil{sleep 0.5;!(varGunner)};
	[] call RUM_AHelBobDwnLocal;
};
if (true) exitwith {};
